package com._21cn.cms.article.utils;

import com._21cn.cms.article.Constants;
import com._21cn.cms.article.entity.*;
import com._21cn.cms.article.service.ArticleService;
import com._21cn.cms.article.service.ColumnArticleService;
import com._21cn.cms.article.service.RegionArticleService;
import com._21cn.cms.common.utils.DocumentUtil;
import com._21cn.cms.resource.utils.PictureUtil;
import com._21cn.cms.site.entity.Column;
import com._21cn.cms.site.entity.Region;
import com._21cn.cms.site.service.ColumnService;
import com._21cn.cms.site.service.RegionService;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.utils.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by Thinkpad on 2017/3/30.
 */
@Component
public class ArticleHelper {

    @Autowired(required = false)
    private ColumnService columnService;

    @Autowired(required = false)
    private RegionService regionService;

    @Autowired(required = false)
    private ArticleService articleService;

    @Autowired(required = false)
    private ColumnArticleService columnArticleService;

    @Autowired(required = false)
    private RegionArticleService regionArticleService;

    @Autowired(required = false)
    private PublishHelper publishHelper;

    /**
     * 格式化文章
     *
     * @param article
     * @return
     */
    public Article regulate4Save(Article article) {
        //设置站点信息
        regulateSiteInfo(article);
        //设置链接
        article.regulateArticleUrl();
        // 设置摘要
        if (StringUtil.isEmpty(article.getSummary())) {
            article.setSummaryFlag(Constants.SUMMARY_FLAG_HAS_SUMMARY);
            article.setSummary(ArticleUtil.formatSummary(article.getContent(), Constants.DEFAULT_SUMMARY_LENGTH));
        }else {
            article.setSummaryFlag(Constants.SUMMARY_FLAG_NO_SUMMARY);
        }
        // 设置短标题
        if (StringUtil.isEmpty(article.getTitleShort())) {
            article.setTitleShort(article.getTitle());
        }
        // 提取文章图片列表and首图
        if (!StringUtil.isEmpty(article.getContent())) {
            article.setArticlePictureList(extractPictureListFromContent(article));
            List<ArticlePicture> articlePictureList = article.getArticlePictureList();
            if( !articlePictureList.isEmpty() ){
                article.setPicFlag(Constants.PIC_FLAG_HAVE_PIC);
                article.setFirstPicUrl(articlePictureList.get(0).getPicUrl());
            }else{
                article.setPicFlag(Constants.PIC_FLAG_NO_PIC);
            }
        }
        // 设置缩略图
        if (!StringUtil.isEmpty(article.getThumbPicUrlListStr())) {
            List<ArticleThumbPicture> articleThumbPictureList = extractThumbPicListFromJson(article);
            if(articleThumbPictureList.size()>0){
                article.setArticleThumbPictureList(articleThumbPictureList);
            }
        }
        return article;
    }

    public Article regulate4Show(Article article) {
        article = regulate4Save(article);
        article = regulatePager(article);
        return article;
    }

    public Article regulatePager(Article article){
        if(article.getPageContentList().size()>0){
            return article;
        }

        String content = article.getContent();
        if(StringUtil.isEmpty(content)){
            article.getPageContentList().add(content);
            return article;
        }
        String[] pages = content.split(Constants.PAGER_TAG_START);
        article.getPageContentList().add(pages[0]);

        if (pages.length <= 1)
            return article;

        for (int i = 1; i < pages.length; i++) {
            String pageContent = StringUtil.subString(pages[i], Constants.PAGER_TAG_END, "");

            article.getPageContentList().add(pageContent);
        }
        return article;
    }

    /**
     * 设置站点信息（站点、频道、栏目）
     * @param article
     * @return
     */
    public Article regulateSiteInfo(Article article){
        if(article.getColumnId()>0){
            Column column = columnService.getById(article.getColumnId());
            if( column!=null ){
                article.setColumn(column);                      //栏目
                if( column.getChannel()!=null ){
                    article.setChannel(column.getChannel());    //频道
                }
                if( column.getSite()!=null ){
                    article.setSite(column.getSite());          //站点
                }
            }
        }
        return article;
    }

    /**
     * 从文章内容（或附加摘要）中抽取出图片信息
     *
     * @param article
     * @return
     */
    public List<ArticlePicture> extractPictureListFromContent(Article article) {
        List<ArticlePicture> result = new ArrayList<ArticlePicture>();
        String content = article.getContent();
        if(!StringUtil.isEmpty(content)){
            Document doc = Jsoup.parse(content);
            Elements imgs = doc.getElementsByTag("img");
            int i = 0;
            for (Element img: imgs) {
                ArticlePicture articlePicture = new ArticlePicture();
                articlePicture.initWith(article);
                String picUrl = img.attr("src").trim();     // 图片链接
                articlePicture.setPicUrl(picUrl);
                String title = img.attr("title");           // 图片标题
                if (StringUtil.isEmpty(title)){
                    title = img.attr("alt");
                }
                if (StringUtil.isEmpty(title)){
                    title = article.getTitle();
                }
                articlePicture.setPicTitle(title);
                articlePicture.setOrderNum(++i);
                String hashCode = PictureUtil.getHashCodeFromUrl(articlePicture.getPicUrl());
                articlePicture.setPicHashcode(hashCode);
                article.getArticlePictureList().add(articlePicture);
                result.add(articlePicture);
            }
            article.setContent(doc.body().html());
        }
        return result;
    }

    /**
     * 从文章内容中抽取出缩略图
     *
     * @param article
     * @return
     */
    public List<ArticleThumbPicture> extractThumbPicListFromJson(Article article) {
        List<ArticleThumbPicture> result = new ArrayList<ArticleThumbPicture>();
        if (!StringUtil.isEmpty(article.getThumbPicUrlListStr())) {
            JSONObject jsonObj = JSONObject.parseObject(article.getThumbPicUrlListStr());
            JSONArray picArray = jsonObj.getJSONArray("list");
            int i = 0;
            for (Object json: picArray) {
                ArticleThumbPicture thumbPic = new ArticleThumbPicture();
                thumbPic.initWith(article);
                thumbPic.setPicUrl(json.toString());
                thumbPic.setOrderNum(++i);
                String hashCode = PictureUtil.getHashCodeFromUrl(thumbPic.getPicUrl());
                thumbPic.setPicHashcode(hashCode);
                result.add(thumbPic);
            }
            article.setArticleThumbPictureList(result);
        }
        return result;
    }

    /**
     * 硬复制栏目文章
     * @param column
     * @param article
     */
    public void hardCopyArticle(Column column, Article article){
        if( article == null ||column == null || column.getStatus() == com._21cn.cms.common.Constants.STATUS_CLOSE ||
                column.getChannelId()<=0 || column.getChannel().getStatus() == com._21cn.cms.common.Constants.STATUS_CLOSE ){
            return;
        }
        article.setColumn(column);
        article.setColumnId(column.getId());
        article.setChannelId(column.getChannelId());
        article.setCreateTime(new Date());
        article.regulateArticleUrl();
        articleService.insert(article);
        softCopyArticle(column, article, Constants.PUBLISH_COLUMN_MASTER);  //主栏目

    }

    /**
     * 软复制栏目文章
     * @param column
     * @param article
     */
    public void softCopyArticle(Column column, Article article, Integer slaveFlag){
        if(article==null || column == null || column.getStatus() == com._21cn.cms.common.Constants.STATUS_CLOSE ){
            return;
        }
        ColumnArticle columnArticle = new ColumnArticle();
        columnArticle.initColumnArticle(column, article);
        columnArticle.setSlaveFlag(slaveFlag);
        if(StringUtil.isEmpty(article.getArticleUrl())){
            columnArticle.setArticleUrl(article.getArticleUrl(column));
        }
        columnArticleService.insert(columnArticle);
    }

    /**
     * 设置主栏目名称和一稿多投的名称和id
     * @param article
     * @return
     */
    public Article regulateColumns(Article article){
        //设置主栏目
        if( article.getColumn()!=null ){
            article.setMainColumnId(article.getColumn().getId());
            article.setMainColumn(article.getColumn().getName());
        }else {
            if (article.getColumnId()>0){
                Integer columnId = article.getColumnId();
                Column column = columnService.getById(columnId);
                if( column!=null ){
                    article.setMainColumnId(column.getId());
                    article.setMainColumn(column.getName());
                }
            }
        }
        //设置从栏目
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("eqArticleId", article.getId());
        params.put("eqSlaveFlag", Constants.PUBLISH_COLUMN_SLAVE);
        PageList<ColumnArticle> list = columnArticleService.getList(params, 1, 1000);
        if(!list.isEmpty()){
            StringBuffer relateName = new StringBuffer();
            StringBuffer relateIds = new StringBuffer();
            for(ColumnArticle obj: list){
                Integer columnId = obj.getColumnId();
                Column column = columnService.getById(columnId);
                if (relateName.length() != 0) {
                    relateName.append("," + column.getName());
                    relateIds.append("," + column.getId());
                } else {
                    relateName.append(column.getName());
                    relateIds.append(column.getId());
                }
            }
            article.setRelateColumns(relateName.toString());
            article.setRelateColumnIds(relateIds.toString());
        }else {
            article.setRelateColumns("");
            article.setRelateColumnIds("");
        }
        return article;
    }

    /**
     * 设置区块的名称和id
     * @param article
     * @return
     */
    public Article regulateRegions(Article article){
        //设置从栏目
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("eqArticleId", article.getId());
        PageList<RegionArticle> list = regionArticleService.getList(params, 1, 1000);
        if(!list.isEmpty()){
            StringBuffer regionName = new StringBuffer();
            StringBuffer regionIds = new StringBuffer();
            for(RegionArticle obj: list){
                Integer regionId = obj.getRegionId();
                Region region = regionService.getById(regionId);
                if (regionName.length() != 0) {
                    regionName.append("," + region.getName());
                    regionIds.append("," + region.getId());
                } else {
                    regionName.append(region.getName());
                    regionIds.append(region.getId());
                }
            }
            article.setRegions(regionName.toString());
            article.setRegionIds(regionIds.toString());
        }else {
            article.setRegions("");
            article.setRegionIds("");
        }
        return article;
    }
}
